﻿using System;
using System.Diagnostics;

namespace Mrsoft.Common
{
    /// <summary>
    /// 测试计时器项目
    /// </summary>
    public class Profiler : IDisposable
    {
        private readonly Stopwatch watch;
        private readonly string message;

        private Profiler(string message)
        {
            this.watch = new Stopwatch();
            this.watch.Start();
            this.message = message;
        }

        /// <summary>
        /// 结束计时器输出结果
        /// </summary>
        public void Dispose()
        {
            watch.Stop();
            MsgListener.CommonMsgShow("计时系统", string.Format("{0}用时：{1:0.00} ms", message, 1000.0 * watch.ElapsedTicks / Stopwatch.Frequency));
        }

        /// <summary>
        /// 创建可释放的计时器
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static IDisposable Step(string message)
        {
            return new Profiler(message);
        }

        /// <summary>
        /// 内联函数执行时间计时
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static T Inline<T>(string message, Func<T> func)
        {
            using (new Profiler(message))
                return func();
        }
    }
}